import React, { useEffect, useRef, useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  Dimensions,
  Platform,
} from 'react-native';
import { Portal } from '@gorhom/portal';

interface PortalDropdownProps {
  visible: boolean;
  onClose: () => void;
  options: Array<{ value: any; label: string }>;
  selectedValues: any[];
  onSelect: (value: any) => void;
  triggerRef: React.RefObject<View | null>;
  placeholder?: string;
  multiple?: boolean;
}

const PortalDropdown: React.FC<PortalDropdownProps> = ({
  visible,
  onClose,
  options,
  selectedValues,
  onSelect,
  triggerRef,
  placeholder = '请选择',
  multiple = false,
}) => {
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 });
  const [screenHeight, setScreenHeight] = useState(Dimensions.get('window').height);

  useEffect(() => {
    if (visible && triggerRef.current) {
      // 添加延迟确保DOM完全渲染
      setTimeout(() => {
        measureTriggerPosition();
      }, 50);
    }
  }, [visible]);

  const measureTriggerPosition = () => {
    if (triggerRef.current) {
      // 使用measure方法替代measureInWindow，在小米手机上更稳定
      triggerRef.current.measure((x, y, width, height, pageX, pageY) => {
        const dropdownTop = pageY + height + 5; // 5px 间距
        const dropdownLeft = pageX;
        const dropdownWidth = width;
        
        // 检查是否超出屏幕底部
        const maxHeight = 200;
        const availableHeight = screenHeight - dropdownTop;
        const actualHeight = Math.min(maxHeight, availableHeight);
        
        // 小米手机特殊处理：增加额外的偏移量
        const adjustedTop = Platform.OS === 'android' ? dropdownTop  : dropdownTop;
        
        // 确保下拉框不会超出屏幕右边界
        const screenWidth = Dimensions.get('window').width;
        const adjustedLeft = Math.max(0, Math.min(dropdownLeft, screenWidth - dropdownWidth - 10));
        
        setDropdownPosition({
          top: adjustedTop,
          left: adjustedLeft,
          width: dropdownWidth,
        });
      });
    }
  };

  const handleSelect = (value: any) => {
    onSelect(value);
    if (!multiple) {
      onClose();
    }
  };

  const isSelected = (value: any) => {
    return selectedValues.includes(value);
  };

  if (!visible) return null;

  return (
    <Portal>
      <TouchableOpacity
        style={styles.overlay}
        activeOpacity={1}
        onPress={onClose}
      >
        <View
          style={[
            styles.dropdown,
            {
              top: dropdownPosition.top,
              left: dropdownPosition.left,
              width: dropdownPosition.width,
            },
          ]}
        >
          <ScrollView 
            showsVerticalScrollIndicator={false}
            style={styles.scrollView}
            nestedScrollEnabled={true}
          >
            {options.map((option) => (
              <TouchableOpacity
                key={option.value}
                style={[
                  styles.option,
                  isSelected(option.value) && styles.optionSelected,
                ]}
                onPress={() => handleSelect(option.value)}
              >
                <Text
                  style={[
                    styles.optionText,
                    isSelected(option.value) && styles.optionTextSelected,
                  ]}
                >
                  {option.label}
                </Text>
                {isSelected(option.value) && (
                  <Text style={styles.checkmark}>✓</Text>
                )}
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>
      </TouchableOpacity>
    </Portal>
  );
};

const styles = StyleSheet.create({
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'transparent',
    zIndex: Platform.OS === 'android' ? 9999999 : 9999,
  },
  dropdown: {
    position: 'absolute',
    backgroundColor: '#fff',
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ddd',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 6,
    elevation: Platform.OS === 'android' ? 100 : 4,
    zIndex: Platform.OS === 'android' ? 10000000 : 10000,
    maxHeight: 200,
  },
  scrollView: {
    maxHeight: 200,
  },
  option: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  optionSelected: {
    backgroundColor: '#f0f8ff',
  },
  optionText: {
    fontSize: 16,
    color: '#333',
  },
  optionTextSelected: {
    color: '#0076ff',
    fontWeight: 'bold',
  },
  checkmark: {
    fontSize: 20,
    color: '#0076ff',
    textAlignVertical: 'center',
    includeFontPadding: false,
  },
});

export default PortalDropdown; 